package cn.edu.xjtu.nbrash.xbarsuite.zxingdemo;

import java.io.FileNotFoundException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import cn.edu.xjtu.nbrash.xbarsuite.R;
import cn.edu.xjtu.nbrash.xbarsuite.utilities.Utilities;

import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;

public class ScanFromImageActivity extends Activity {

	private static final int RC_SELECT_AN_IMAGE = 1314;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_scan_from_image);
	}

	public void selectAnImage(View v) {
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(intent, RC_SELECT_AN_IMAGE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
				case RC_SELECT_AN_IMAGE:
					try {
						Uri uri = data.getData();
						ContentResolver contentResolver = this
								.getContentResolver();
						Bitmap bitmap = BitmapFactory
								.decodeStream(contentResolver
										.openInputStream(uri));
						MultiFormatReader multiFormatReader = new MultiFormatReader();
						Result result = multiFormatReader.decode(Utilities
								.bitmap2BinaryBitmap(bitmap));
						String text = result.getText();
						this.alertDialog("解码结果为：", text);
					} catch (FileNotFoundException e) {
						this.alertWarningDialog("图片不见掉了！");
						e.printStackTrace();
					} catch (NotFoundException e) {
						this.alertWarningDialog("咦，没有发现二维码！");
						e.printStackTrace();
					}
					break;

				default:
					break;
			}
		}

	}

	private void alertDialog(String titile, String message) {
		new AlertDialog.Builder(this).setTitle(titile).setMessage(message)
				.show();
	}

	private void alertWarningDialog(String warning) {
		this.alertDialog("Warning", warning);
	}
}
